<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description">
<meta property="og:type" content="website">
<meta property="og:title" content="Hexo">
<meta property="og:url" content="http://yoursite.com/page/6/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hexo">
<meta name="twitter:description">
  
    <link rel="alternative" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css" type="text/css">
  

</head>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main">
  
    <article id="post-zookeeper/2.zookeeper系列之原理" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/09/zookeeper/2.zookeeper系列之原理/" class="article-date">
  <time datetime="2016-01-08T18:00:00.000Z" itemprop="datePublished">2016-01-09</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/zookeeper/">zookeeper</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/09/zookeeper/2.zookeeper系列之原理/">zookeeper系列二之原理</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u57FA_u672C_u6982_u5FF5"><a href="#u57FA_u672C_u6982_u5FF5" class="headerlink" title="基本概念"></a>基本概念</h2><h4 id="u89D2_u8272"><a href="#u89D2_u8272" class="headerlink" title="角色"></a>角色</h4><p>　　Zookeeper中的角色主要有以下三类，如下表所示：</p>
<table>
<thead>
<tr>
<th style="text-align:left">角色</th>
<th style="text-align:left">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">Leader</td>
<td style="text-align:left">负责投票的发起和决议，更新系统状态</td>
</tr>
<tr>
<td style="text-align:left">Follower</td>
<td style="text-align:left">接收客户端请求并想客户端返回结果，在选主过程中参与投票</td>
</tr>
<tr>
<td style="text-align:left">Observer</td>
<td style="text-align:left">接收客户端连接，将写请求转发给leader节点。<br>但Observer不参与投票过程，只同步leader的状态。<br>Observer的目的是为了扩展系统，提高读取速度。</td>
</tr>
<tr>
<td style="text-align:left">Client</td>
<td style="text-align:left">请求发起方</td>
</tr>
</tbody>
</table>
<h4 id="u8BBE_u8BA1_u76EE_u7684"><a href="#u8BBE_u8BA1_u76EE_u7684" class="headerlink" title="设计目的"></a>设计目的</h4><p>　　1. 最终一致性：client不论连接到哪个Server，展示给它都是同一个视图，这是zookeeper最重要的性能。<br>　　2. 可靠性：具有简单、健壮、良好的性能，如果消息m被到一台服务器接收，那么它将被所有的服务器接收。<br>　　3. 实时性：Zookeeper保证客户端将在一个时间间隔范围内获得服务器的更新信息，或者服务器失效的信息。但由于网络延时等原因，Zookeeper不能保证两个客户端能同时得到刚更新的数据，如果需要最新数据，应该在读数据之前调用sync()接口。<br>　　4. 等待无关（wait-free）：慢的或者失效的client不得干预快速的client的请求，使得每个client都能有效的等待。<br>　　5. 原子性：更新只能成功或者失败，没有中间状态。<br>　　6. 顺序性：包括全局有序和偏序两种：全局有序是指如果在一台服务器上消息a在消息b前发布，则在所有Server上消息a都将在消息b前被发布；偏序是指如果一个消息b在消息a后被同一个发送者发布，a必将排在b前面。</p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2><p><a href="http://cailin.iteye.com/blog/2014486" target="_blank" rel="external">http://cailin.iteye.com/blog/2014486</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/09/zookeeper/2.zookeeper系列之原理/" data-id="cijzzpv0q000o1cfsjp9vblio" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/zookeeper/">zookeeper</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-zookeeper/1.zookeeper系列之入门" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/09/zookeeper/1.zookeeper系列之入门/" class="article-date">
  <time datetime="2016-01-08T17:00:00.000Z" itemprop="datePublished">2016-01-09</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/zookeeper/">zookeeper</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/09/zookeeper/1.zookeeper系列之入门/">zookeeper系列一之入门</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　ZooKeeper是一个分布式的，开放源码的分布式应用程序协调服务，它包含一个简单的原语集，分布式应用程序可以基于它实现同步服务，配置维护和命名服务等。在分布式应用中，由于工程师不能很好地使用锁机制，以及基于消息的协调机制不适合在某些应用中使用，因此需要有一种可靠的、可扩展的、分布式的、可配置的协调机制来统一系统的状态。Zookeeper的目的就在于此。本文先介绍如何使用zookeeper，后文再介绍其运行原理</p>
<h2 id="u5355_u8282_u70B9_u73AF_u5883_u642D_u5EFA"><a href="#u5355_u8282_u70B9_u73AF_u5883_u642D_u5EFA" class="headerlink" title="单节点环境搭建"></a>单节点环境搭建</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#zookeeper-3.4.5.tar.gz解压至/usr/local目录下</span></span><br><span class="line">tar -zxvf zookeeper-<span class="number">3.4</span>.<span class="number">5</span>.tar.gz</span><br><span class="line">mv zookeeper-<span class="number">3.4</span>.<span class="number">5</span> zookeeper</span><br><span class="line"></span><br><span class="line"><span class="comment">#新建zookeeper/conf/zoo.cfg文件：</span></span><br><span class="line">cp zoo_sample.cfg zoo.cfg</span><br><span class="line"><span class="comment">#并作如下修改，其他保持不变，并建立相应的文件夹</span></span><br><span class="line">dataDir=/usr/<span class="built_in">local</span>/zookeeper/data </span><br><span class="line">dataLogDir/usr/<span class="built_in">local</span>/zookeeper/<span class="built_in">log</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#配置环境变量：</span></span><br><span class="line"><span class="built_in">export</span> ZOOKEEPER_HOME=/usr/<span class="built_in">local</span>/zookeeper</span><br><span class="line"><span class="built_in">export</span> PATH=<span class="variable">$ZOOKEEPER_HOME</span>/bin:<span class="variable">$PATH</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#启动zookeeper服务</span></span><br><span class="line">bin/zkServer.sh start</span><br><span class="line"><span class="comment">#注意：在3.4.6版本的Windows环境下实测，启动命令为zkServer.cmd，没有参数start，</span></span><br><span class="line"><span class="comment">#否则会抛出异常java.lang.NumberFormatException: For input string: "D:\zookeeper-3.4.6\bin\..\co nf\zoo.cfg"</span></span><br></pre></td></tr></table></figure>
<h2 id="u591A_u673A_u96C6_u7FA4_u73AF_u5883_u642D_u5EFA"><a href="#u591A_u673A_u96C6_u7FA4_u73AF_u5883_u642D_u5EFA" class="headerlink" title="多机集群环境搭建"></a>多机集群环境搭建</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#修改conf/zoo.cfg配置文件如下</span></span><br><span class="line"><span class="comment"># The number of milliseconds of each tick</span></span><br><span class="line">tickTime=<span class="number">2000</span></span><br><span class="line"><span class="comment"># The number of ticks that the initial </span></span><br><span class="line"><span class="comment"># synchronization phase can take</span></span><br><span class="line">initLimit=<span class="number">10</span></span><br><span class="line"><span class="comment"># The number of ticks that can pass between </span></span><br><span class="line"><span class="comment"># sending a request and getting an acknowledgement</span></span><br><span class="line">syncLimit=<span class="number">5</span></span><br><span class="line"><span class="comment"># the directory where the snapshot is stored.</span></span><br><span class="line"><span class="comment"># do not use /tmp for storage, /tmp here is just </span></span><br><span class="line"><span class="comment"># example sakes.</span></span><br><span class="line">dataDir=/usr/<span class="built_in">local</span>/zookeeper-<span class="number">3.4</span>.<span class="number">6</span>/dataDir</span><br><span class="line">dataLogDir=/usr/<span class="built_in">local</span>/zookeeper-<span class="number">3.4</span>.<span class="number">6</span>/dataLogDir</span><br><span class="line"><span class="comment"># the port at which the clients will connect</span></span><br><span class="line">clientPort=<span class="number">2181</span></span><br><span class="line"><span class="comment"># the maximum number of client connections.</span></span><br><span class="line"><span class="comment"># increase this if you need to handle more clients</span></span><br><span class="line"><span class="comment">#maxClientCnxns=60</span></span><br><span class="line"><span class="comment"># The number of snapshots to retain in dataDir</span></span><br><span class="line"><span class="comment">#autopurge.snapRetainCount=3</span></span><br><span class="line"><span class="comment"># Purge task interval in hours</span></span><br><span class="line"><span class="comment"># Set to "0" to disable auto purge feature</span></span><br><span class="line"><span class="comment">#autopurge.purgeInterval=1</span></span><br><span class="line"><span class="comment">#主要是增加这三行(开始配置为主机名，存在问题，后改为ip地址)</span></span><br><span class="line">server.<span class="number">1</span>=<span class="number">192.168</span>.<span class="number">241.129</span>:<span class="number">2888</span>:<span class="number">3888</span></span><br><span class="line">server.<span class="number">2</span>=<span class="number">192.168</span>.<span class="number">241.130</span>:<span class="number">2888</span>:<span class="number">3888</span></span><br><span class="line">server.<span class="number">3</span>=<span class="number">192.168</span>.<span class="number">241.131</span>:<span class="number">2888</span>:<span class="number">3888</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#规则为：server.id=host:port1:port2</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#id是zookeeper集群各服务器的的id，host是各服务器ip或者主机名，</span></span><br><span class="line"><span class="comment">#port1是各服务器交互信息的端口，port2是当集群中的leader挂掉后重新选举的端口</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#各个服务器id是由myid文件指定，myid需要自己创建，文件只含一个数字，即id，范围为1-255</span></span><br><span class="line"><span class="comment">#myid文件路径为zoo.cfg里的dataDir目录</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#配置完毕，通过bin/zkServer.sh start启动服务，三个机器上都需要执行</span></span><br><span class="line"><span class="comment">#检查配置是否成功</span></span><br><span class="line">/usr/<span class="built_in">local</span>/zookeeper-<span class="number">3.4</span>.<span class="number">6</span>/zookeeper.out文件中查看时候一直存在异常信息输出</span><br></pre></td></tr></table></figure>
<h2 id="u6570_u636E_u64CD_u4F5C"><a href="#u6570_u636E_u64CD_u4F5C" class="headerlink" title="数据操作"></a>数据操作</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#客户端连接zookeeper服务，此时进入客户端交互界面</span></span><br><span class="line"><span class="variable">$bin</span>/zkCli.sh -server localhost:<span class="number">2181</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#查看节点（列出指定node的子node）：ls</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">5</span>] ls /</span><br><span class="line">[zookeeper]</span><br><span class="line"></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">5</span>] ls /hello</span><br><span class="line">[]</span><br><span class="line"></span><br><span class="line"><span class="comment">#创建一个测试节点hello 关联数据world</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">6</span>] create /hello world</span><br><span class="line">Created /hello</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">7</span>] ls /</span><br><span class="line">[hello, zookeeper]</span><br><span class="line"></span><br><span class="line"><span class="comment">#查看节点hello</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">8</span>] get /hello</span><br><span class="line">world</span><br><span class="line">cZxid = <span class="number">0</span>x8</span><br><span class="line">ctime = Fri Apr <span class="number">10</span> <span class="number">13</span>:<span class="number">27</span>:<span class="number">35</span> CST <span class="number">2015</span></span><br><span class="line">mZxid = <span class="number">0</span>x8</span><br><span class="line">mtime = Fri Apr <span class="number">10</span> <span class="number">13</span>:<span class="number">27</span>:<span class="number">35</span> CST <span class="number">2015</span></span><br><span class="line">pZxid = <span class="number">0</span>x8</span><br><span class="line">cversion = <span class="number">0</span></span><br><span class="line">dataVersion = <span class="number">0</span></span><br><span class="line">aclVersion = <span class="number">0</span></span><br><span class="line">ephemeralOwner = <span class="number">0</span>x0</span><br><span class="line">dataLength = <span class="number">5</span></span><br><span class="line">numChildren = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#修改hello节点关联的数据</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">9</span>] <span class="built_in">set</span> /hello new_world</span><br><span class="line">cZxid = <span class="number">0</span>x8</span><br><span class="line">ctime = Fri Apr <span class="number">10</span> <span class="number">13</span>:<span class="number">27</span>:<span class="number">35</span> CST <span class="number">2015</span></span><br><span class="line">mZxid = <span class="number">0</span>x9</span><br><span class="line">mtime = Fri Apr <span class="number">10</span> <span class="number">13</span>:<span class="number">30</span>:<span class="number">22</span> CST <span class="number">2015</span></span><br><span class="line">pZxid = <span class="number">0</span>x8</span><br><span class="line">cversion = <span class="number">0</span></span><br><span class="line">dataVersion = <span class="number">1</span> <span class="comment">#与第6步相比增加了1</span></span><br><span class="line">aclVersion = <span class="number">0</span></span><br><span class="line">ephemeralOwner = <span class="number">0</span>x0</span><br><span class="line">dataLength = <span class="number">9</span> <span class="comment">#new_world的字节数</span></span><br><span class="line">numChildren = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">10</span>] get /hello</span><br><span class="line">new_world</span><br><span class="line">cZxid = <span class="number">0</span>x8</span><br><span class="line">ctime = Fri Apr <span class="number">10</span> <span class="number">13</span>:<span class="number">27</span>:<span class="number">35</span> CST <span class="number">2015</span></span><br><span class="line">mZxid = <span class="number">0</span>x9</span><br><span class="line">mtime = Fri Apr <span class="number">10</span> <span class="number">13</span>:<span class="number">30</span>:<span class="number">22</span> CST <span class="number">2015</span></span><br><span class="line">pZxid = <span class="number">0</span>x8</span><br><span class="line">cversion = <span class="number">0</span></span><br><span class="line">dataVersion = <span class="number">1</span></span><br><span class="line">aclVersion = <span class="number">0</span></span><br><span class="line">ephemeralOwner = <span class="number">0</span>x0</span><br><span class="line">dataLength = <span class="number">9</span></span><br><span class="line">numChildren = <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#删除节点</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">11</span>] delete /hello</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">12</span>] ls /</span><br><span class="line">[zookeeper]</span><br><span class="line"><span class="comment">#使用delete命令可以删除指定znode。当该znode拥有子znode时, 必须先删除其所有子znode, 否则操作将失败。</span></span><br><span class="line"><span class="comment">#rmr命令可用于代替delete命令, rmr是一个递归删除命令, 如果发生指定节点拥有子节点时, rmr命令会首先删除子节点.</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#创建子节点</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">17</span>] ls /</span><br><span class="line">[zookeeper]</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">18</span>] create /hello world  <span class="comment">#创建节点时必须带上关联的数据</span></span><br><span class="line">Created /hello</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">19</span>] create /hello/child child_world <span class="comment">#必须先创建节点hello，再创建child</span></span><br><span class="line">Created /hello/child</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">20</span>] ls /</span><br><span class="line">[hello, zookeeper]</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">21</span>] ls /hello</span><br><span class="line">[child]</span><br></pre></td></tr></table></figure>
<h2 id="u8282_u70B9_u5143_u6570_u636E"><a href="#u8282_u70B9_u5143_u6570_u636E" class="headerlink" title="节点元数据"></a>节点元数据</h2><p>　　在zookeeper中每个节点称为一个znode. 每个znode由3部分组成<br>　　1. stat：此为状态信息，描述该znode的版本，权限等信息<br>　　2. data：与该znode关联的数据<br>　　3. children：该znode下的子节点<br>　　在上面的操作中，使用了get命令获取指定节点的数据时，同时也返回了该节点的状态信息，称为Stat，其包含如下字段:<br>　　1. czxid：节点创建时的zxid<br>　　2. ctime：节点创建时的时间戳<br>　　3. mzxid：节点最新一次更新发生时的zxid<br>　　4. mtime：节点最新一次更新发生时的时间戳<br>　　5. dataVersion：节点数据的更新次数<br>　　6. cversion：其子节点的更新次数<br>　　7. aclVersion：节点ACL(授权信息)的更新次数<br>　　8. ephemeralOwner：如果该节点为ephemeral节点，ephemeralOwner值表示与该节点绑定的session id。如果该节点不是ephemeral节点，ephemeralOwner值为0。至于什么是ephemeral节点，请看后面的讲述<br>　　9. dataLength：节点数据的字节数<br>　　10. numChildren：子节点个数</p>
<h4 id="zxid"><a href="#zxid" class="headerlink" title="zxid"></a>zxid</h4><p>　　ZooKeeper状态的每一次改变，都对应着一个递增的Transaction id，该id称为zxid。由于zxid的递增性质，如果zxid1小于zxid2，那么zxid1肯定先于zxid2发生。创建任意节点，或者更新任意节点的数据，或者删除任意节点，都会导致Zookeeper状态发生改变，从而导致zxid的值增加。</p>
<h4 id="session"><a href="#session" class="headerlink" title="session"></a>session</h4><p>　　在client和server通信之前，首先需要建立连接，该连接称为session。连接建立后，如果发生连接超时，授权失败，或者显式关闭连接，连接便处于CLOSED状态，此时session结束。</p>
<h2 id="u8282_u70B9_u7C7B_u578B"><a href="#u8282_u70B9_u7C7B_u578B" class="headerlink" title="节点类型"></a>节点类型</h2><p>　　讲述节点状态的ephemeralOwner字段时，提到过有的节点是ephemeral节点，而有的并不是。那么节点都具有哪些类型呢，每种类型的节点又具有哪些特点呢？<br>　　1. persistent：persistent节点不和特定的session绑定，不会随着创建该节点的session的结束而消失，而是一直存在，除非该节点被显式删除。<br>　　2. ephemeral：ephemeral节点是临时性的，如果创建该节点的session结束了，该节点就会被自动删除，ephemeral节点不能拥有子节点。虽然ephemeral节点与创建它的session绑定，但只要该节点没有被删除，其他session就可以读写该节点中关联的数据。使用-e参数指定创建ephemeral节点（create -e /xing/ei world），其应用场景主要包括：<br>　　<strong>分布式集群是否存活监控</strong>：每个节点启动后，注册一个EPHEMERAL节点到zookeeper中，注册一个Watcher获取EPHEMERAL节点的存在情况，消失即可代表集群节点dead)<br>　　<strong>分布式lock</strong>：每个锁竞争者，排队时都在zookeeper中注册一个EPHEMERAL节点，排队过程中有节点dead了，zookeeper可以自动将其剔除队列，避免出现deadlock<br>　　<strong>替代web服务器的session</strong>：实现一个集中式session，session数据中的setAttribute都创建为EPHEMERAL节点，session关闭后即可自动删除，不会造成java中的内存泄漏<br>　　3. sequence：严格的说，sequence并非节点类型中的一种。sequence节点既可以是ephemeral的，也可以是persistent的。创建sequence节点时，ZooKeeper Server会在指定的节点名称后加上一个数字序列，该数字序列是递增的。因此可以多次创建相同的sequence节点，而得到不同的节点。使用-s参数指定创建sequence节点。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[zk: localhost:<span class="number">4180</span>(CONNECTED) <span class="number">2</span>] create <span class="operator">-s</span> /snode world</span><br><span class="line">Created /xing/item0000000003</span><br><span class="line">[zk: localhost:<span class="number">4180</span>(CONNECTED) <span class="number">3</span>] create <span class="operator">-s</span> /snode world</span><br><span class="line">Created /xing/item0000000004</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">33</span>] ls /</span><br><span class="line">[hello, snode0000000003, zookeeper, snode0000000004]</span><br></pre></td></tr></table></figure></p>
<h2 id="u4E8B_u4EF6_u76D1_u542C"><a href="#u4E8B_u4EF6_u76D1_u542C" class="headerlink" title="事件监听"></a>事件监听</h2><p>　　watch的意思是监听感兴趣的事件，在命令行中，以下几个命令可以指定是否监听相应的事件：</p>
<h4 id="ls_u547D_u4EE4"><a href="#ls_u547D_u4EE4" class="headerlink" title="ls命令"></a>ls命令</h4><p>　　ls命令的第一个参数指定znode，第二个参数如果为true，则说明监听该znode的子节点的增减，以及该znode本身的删除事件（实测没有）<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">41</span>] create /<span class="built_in">test</span> tt</span><br><span class="line">Created /<span class="built_in">test</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">42</span>] ls /<span class="built_in">test</span> <span class="literal">true</span></span><br><span class="line">[]</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">43</span>] create /<span class="built_in">test</span>/child c  <span class="comment">#监听子节点的添加</span></span><br><span class="line">WATCHER::</span><br><span class="line">WatchedEvent state:SyncConnected <span class="built_in">type</span>:NodeChildrenChanged path:/<span class="built_in">test</span></span><br><span class="line">Created /<span class="built_in">test</span>/child</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">44</span>] <span class="built_in">set</span> /<span class="built_in">test</span> new_tt  <span class="comment">#更新节点并未触发事件</span></span><br><span class="line">cZxid = <span class="number">0</span>x19</span><br><span class="line">ctime = Fri Apr <span class="number">10</span> <span class="number">14</span>:<span class="number">19</span>:<span class="number">28</span> CST <span class="number">2015</span></span><br><span class="line">mZxid = <span class="number">0</span>x1b</span><br><span class="line">mtime = Fri Apr <span class="number">10</span> <span class="number">14</span>:<span class="number">20</span>:<span class="number">07</span> CST <span class="number">2015</span></span><br><span class="line">pZxid = <span class="number">0</span>x1a</span><br><span class="line">cversion = <span class="number">1</span></span><br><span class="line">dataVersion = <span class="number">1</span></span><br><span class="line">aclVersion = <span class="number">0</span></span><br><span class="line">ephemeralOwner = <span class="number">0</span>x0</span><br><span class="line">dataLength = <span class="number">6</span></span><br><span class="line">numChildren = <span class="number">1</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">45</span>] delete /<span class="built_in">test</span>/child <span class="comment">#删除节点也未触发事件</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">46</span>] delete /<span class="built_in">test</span></span><br></pre></td></tr></table></figure></p>
<h4 id="get_u547D_u4EE4"><a href="#get_u547D_u4EE4" class="headerlink" title="get命令"></a>get命令</h4><p>　　get命令的第一个参数指定znode，第二个参数如果为true，则说明监听该znode的更新和删除事件<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">35</span>] get /hello <span class="literal">true</span></span><br><span class="line">world</span><br><span class="line">cZxid = <span class="number">0</span>xb</span><br><span class="line">ctime = Fri Apr <span class="number">10</span> <span class="number">14</span>:<span class="number">00</span>:<span class="number">17</span> CST <span class="number">2015</span></span><br><span class="line">mZxid = <span class="number">0</span>xb</span><br><span class="line">mtime = Fri Apr <span class="number">10</span> <span class="number">14</span>:<span class="number">00</span>:<span class="number">17</span> CST <span class="number">2015</span></span><br><span class="line">pZxid = <span class="number">0</span>xc</span><br><span class="line">cversion = <span class="number">1</span></span><br><span class="line">dataVersion = <span class="number">0</span></span><br><span class="line">aclVersion = <span class="number">0</span></span><br><span class="line">ephemeralOwner = <span class="number">0</span>x0</span><br><span class="line">dataLength = <span class="number">5</span></span><br><span class="line">numChildren = <span class="number">1</span></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">36</span>] create /hello/c cc  <span class="comment">#创建子节点，并未触发监听事件</span></span><br><span class="line">Created /hello/c</span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">40</span>] <span class="built_in">set</span> /hello new_t    <span class="comment">#修改节点数据，触发监听事件</span></span><br><span class="line">WATCHER::</span><br><span class="line">WatchedEvent state:SyncConnected <span class="built_in">type</span>:NodeDataChanged path:/hello</span><br><span class="line">cZxid = <span class="number">0</span>x17</span><br><span class="line">ctime = Fri Apr <span class="number">10</span> <span class="number">14</span>:<span class="number">14</span>:<span class="number">58</span> CST <span class="number">2015</span></span><br><span class="line">mZxid = <span class="number">0</span>x18</span><br><span class="line">mtime = Fri Apr <span class="number">10</span> <span class="number">14</span>:<span class="number">15</span>:<span class="number">30</span> CST <span class="number">2015</span></span><br><span class="line">pZxid = <span class="number">0</span>x17</span><br><span class="line">cversion = <span class="number">0</span></span><br><span class="line">dataVersion = <span class="number">1</span></span><br><span class="line">aclVersion = <span class="number">0</span></span><br><span class="line">ephemeralOwner = <span class="number">0</span>x0</span><br><span class="line">dataLength = <span class="number">5</span></span><br><span class="line">numChildren = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">[zk: localhost:<span class="number">2181</span>(CONNECTED) <span class="number">37</span>] rmr /hello  <span class="comment">#删除节点，触发监听事件</span></span><br><span class="line">WATCHER::</span><br><span class="line">WatchedEvent state:SyncConnected <span class="built_in">type</span>:NodeDeleted path:/hello</span><br></pre></td></tr></table></figure></p>
<p>　　总结：<br>　　get：监听节点的删除和修改，添加子节点不会触发事件<br>　　ls：监听子节点的添加，删除和更新节点并不会触发事件<br>　　如需监听子节点，get和ls只需要指定子节点即可，如：get /node/child true<br>　　一次注册只能监听一次事件，每次监听后重新注册时间？</p>
<h4 id="stat_u547D_u4EE4"><a href="#stat_u547D_u4EE4" class="headerlink" title="stat命令"></a>stat命令</h4><p>　　stat命令用于获取znode的状态信息，第一个参数指定znode，如果第二个参数为true，则监听该node的更新和删除事件。</p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2><p><a href="http://www.cnblogs.com/Xrinehart/p/3512509.html" target="_blank" rel="external">http://www.cnblogs.com/Xrinehart/p/3512509.html</a><br><a href="http://blog.csdn.net/lastsweetop/article/details/8794473" target="_blank" rel="external">http://blog.csdn.net/lastsweetop/article/details/8794473</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/09/zookeeper/1.zookeeper系列之入门/" data-id="cijzzpv0u000t1cfsmjtls9zk" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/zookeeper/">zookeeper</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-cache/3.Cache系列之一致性哈希算法" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/08/cache/3.Cache系列之一致性哈希算法/" class="article-date">
  <time datetime="2016-01-07T19:00:00.000Z" itemprop="datePublished">2016-01-08</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/cache/">cache</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/08/cache/3.Cache系列之一致性哈希算法/">Cache系列三之一致性哈希算法</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u80CC_u666F"><a href="#u80CC_u666F" class="headerlink" title="背景"></a>背景</h2><p>　　随着网站用户增多、流量增大、查询请求增多，缓存服务器的压力也逐渐增大，需要越来越多的缓存服务器满足性能要求，同时需要缓存的数据量也越来越大，单台机器无法满足存储需求，此时就面临服务器的扩展和数据拆分问题。如何减少缓存服务器的部署成本和保证原有缓存服务器数据的有效性成为一个值得思考的问题！下面我们就谈谈一致性哈希算法在该应用场景中的优势！</p>
<h2 id="u666E_u901Ahash_u7B97_u6CD5"><a href="#u666E_u901Ahash_u7B97_u6CD5" class="headerlink" title="普通hash算法"></a>普通hash算法</h2><p>　　保证对相同key的访问会被发送到相同的服务器，最常用的方法是计算哈希。例如对于每次访问，可以按算法（h = Hash(key) % 3）计算其哈希值，其中Hash是一个从字符串到正整数的哈希映射函数。这样，如果我们将Memcached Server分别编号为0、1、2，那么就可以根据上式和key计算出服务器编号h，然后去访问。将该方法抽象，可以认为通过：h = Hash(key) % N。这个算式计算每个key的请求应该被发送到哪台服务器，其中N为服务器的台数，并且服务器按照0 – (N-1)编号。<br>　　该算法在容错性和扩展性方面不好。所谓容错性是指当系统中某一个或几个服务器变得不可用时，整个系统是否可以正确高效运行；而扩展性是指当加入新的服务器后，整个系统是否可以正确高效运行。<br>　　现假设有一台服务器宕机了，那么为了填补空缺，要将宕机的服务器从编号列表中移除，后面的服务器按顺序前移一位并将其编号值减一，此时每个key就要按h = Hash(key) % (N-1)重新计算；同样，如果新增了一台服务器，虽然原有服务器编号不用改变，但是要按h = Hash(key) % (N+1)重新计算哈希值。因此<strong>系统中一旦有服务器变更，大量的key会被重定位到不同的服务器从而造成大量的缓存不命中</strong>。而这种情况在分布式系统中是非常糟糕的。一个设计良好的分布式哈希方案应该具有良好的单调性，即<strong>服务节点的增减不会造成大量哈希重定位</strong>，一致性哈希算法就是这样一种哈希方案。</p>
<h2 id="u4E00_u81F4_u6027_u54C8_u5E0C_u7B97_u6CD5"><a href="#u4E00_u81F4_u6027_u54C8_u5E0C_u7B97_u6CD5" class="headerlink" title="一致性哈希算法"></a>一致性哈希算法</h2><p>　　基本原理：将机器节点和key值都按照一样的hash算法映射到一个0~2^32的圆环上。一致性hash算法提出了在动态变化的缓存环境中，判定哈希算法好坏的四个定义：<br>　　1、平衡性(Balance)：平衡性是指哈希的结果能够尽可能分布到所有的缓存服务器中去，这样可以使得所有的缓存空间都得到利用。<br>　　2、单调性(Monotonicity)：单调性是指如果已经有一些内容通过哈希分派到了相应的缓存中，当有新的缓存加入到系统中时，哈希的结果应能够保证<strong>原有已分配的内容可以被映射到原有的或者新的缓存</strong>中去，而不会被映射到旧的缓存集合中的其他缓存区。<br>　　3、分散性(Spread)：在分布式环境中，终端有可能看不到所有的缓存服务器，而是只能看到其中的一部分。当终端希望通过哈希过程将内容映射到缓存上时，由于不同终端所见的缓冲范围有可能不同，从而导致哈希的结果不一致，最终的结果是相同的内容被不同的终端映射到不同的缓冲区中。这种情况显然是应该避免的，因为它导致相同内容被存储到不同缓冲中去，降低了系统存储的效率。分散性的定义就是上述情况发生的严重程度。好的哈希算法应能够尽量避免不一致的情况发生，也就是尽量降低分散性。<br>　　4、负载(Load)：负载问题实际上是从另一个角度看待分散性问题。既然不同的终端可能将相同的内容映射到不同的缓存区中，那么对于一个特定的缓存区而言，也可能被不同的用户映射为不同 的内容。与分散性一样，这种情况也是应当避免的，因此好的哈希算法应能够尽量降低缓存的负荷。<br>　　在分布式集群中，对机器的添加删除，或者机器故障后自动脱离集群这些操作是分布式集群管理最基本的功能。如果采用常用的hash(object)%N算法，那么在有机器添加或者删除后，很多原有的数据就无法找到了，这样严重的违反了单调性原则。接下来主要讲解一下一致性哈希算法是如何设计的：</p>
<h4 id="u73AF_u5F62Hash_u7A7A_u95F4"><a href="#u73AF_u5F62Hash_u7A7A_u95F4" class="headerlink" title="环形Hash空间"></a>环形Hash空间</h4><p>　　按照常用的hash算法来将对应的key哈希到一个具有2^32次方个桶的空间（约4亿多）中，即0~(2^32)-1的数字空间中。现在我们可以将这些数字头尾相连，想象成一个闭合的环形。如下图<img src="/images/411000507734.png" alt="411000507734.png"></p>
<h4 id="u6570_u636Ehash"><a href="#u6570_u636Ehash" class="headerlink" title="数据hash"></a>数据hash</h4><p>　　将object1、object2、object3、object4四个对象通过特定的Hash函数计算出对应的key值，然后散列到Hash环上。如下图：<img src="/images/411000620656.png" alt="411000620656.png"></p>
<h4 id="u673A_u5668hash"><a href="#u673A_u5668hash" class="headerlink" title="机器hash"></a>机器hash</h4><p>　　在采用一致性哈希算法的分布式集群中将新的机器加入，其原理是通过使用与数据存储一样的Hash算法将机器也映射到环中（一般情况下对机器的hash计算是采用机器的IP或者机器唯一的别名作为输入值），然后以顺时针的方向计算，将所有对象存储到离自己最近的机器中。假设现在有NODE1，NODE2，NODE3三台机器，通过Hash算法得到对应的KEY值，映射到环中，其示意图如下：<img src="/images/411000853609.png" alt="411000853609.png"><br>　　通过上图可以看出对象与机器处于同一哈希空间中，这样按顺时针转动object1存储到了NODE1中，object3存储到了NODE2中，object2、object4存储到了NODE3中。在这样的部署环境中，hash环是不会变更的，因此，通过算出对象的hash值就能快速的定位到对应的机器中，这样就能找到对象真正的存储位置了。</p>
<h4 id="u673A_u5668_u7684_u5220_u9664"><a href="#u673A_u5668_u7684_u5220_u9664" class="headerlink" title="机器的删除"></a>机器的删除</h4><p>　　以上面的分布为例，如果NODE2出现故障被删除了，那么按照顺时针迁移的方法，object3将会被迁移到NODE3中，这样仅仅是object3的映射位置发生了变化，其它的对象没有任何的改动。如下图：<img src="/images/411001033656.png" alt="411001033656.png"></p>
<h4 id="u673A_u5668_u7684_u6DFB_u52A0"><a href="#u673A_u5668_u7684_u6DFB_u52A0" class="headerlink" title="机器的添加"></a>机器的添加</h4><p>　　如果往集群中添加一个新的节点NODE4，通过对应的哈希算法得到KEY4，并映射到环中，如下图：<img src="/images/411001211062.png" alt="411001211062.png"><br>　　通过按顺时针迁移的规则，那么object2被迁移到了NODE4中，其它对象还保持这原有的存储位置。通过对节点的添加和删除的分析，一致性哈希算法在保持了单调性的同时，还是数据的迁移达到了最小，这样的算法对分布式集群来说是非常合适的，避免了大量数据迁移，减小了服务器的的压力。</p>
<h2 id="u5E73_u8861_u6027_28_u865A_u62DF_u8282_u70B9_29"><a href="#u5E73_u8861_u6027_28_u865A_u62DF_u8282_u70B9_29" class="headerlink" title="平衡性(虚拟节点)"></a>平衡性(虚拟节点)</h2><p>　　根据上面的图解分析，一致性哈希算法满足了单调性和负载均衡的特性以及一般hash算法的分散性，但这还并不能当做其被广泛应用的原由，因为还缺少了平衡性。下面将分析一致性哈希算法是如何满足平衡性的。hash算法是不保证平衡的，如上面只部署了NODE1和NODE3的情况（NODE2被删除的图），object1存储到了NODE1中，而object2、object3、object4都存储到了NODE3中，这样就照成了非常不平衡的状态。在一致性哈希算法中，为了尽可能的满足平衡性，其引入了虚拟节点。<br>　　“虚拟节点”（ virtual node ）是实际节点（机器）在 hash 空间的复制品（replica），一实际个节点（机器）对应了若干个“虚拟节点”，这个对应个数也成为“复制个数”，“虚拟节点”在 hash 空间中以hash值排列。<br>以上面只部署了NODE1和NODE3的情况（NODE2被删除的图）为例，之前的对象在机器上的分布很不均衡，现在我们以2个副本（复制个数）为例，这样整个hash环中就存在了4个虚拟节点，最后对象映射的关系图如下：<img src="/images/411001433375.png" alt="411001433375.png"><br>　　根据上图可知对象的映射关系：object1-&gt;NODE1-1，object2-&gt;NODE1-2，object3-&gt;NODE3-2，object4-&gt;NODE3-1。通过虚拟节点的引入，对象的分布就比较均衡了。那么在实际操作中，正真的对象查询是如何工作的呢？对象从hash到虚拟节点到实际节点的转换如下图：<img src="/images/411001540656.png" alt="411001540656.png"><br>　　“虚拟节点”的hash计算可以采用对应节点的IP地址加数字后缀的方式。例如假设NODE1的IP地址为192.168.1.100。引入“虚拟节点”前，计算 cache A 的 hash 值：Hash(“192.168.1.100”);引入“虚拟节点”后，计算“虚拟节”点NODE1-1和NODE1-2的hash值：Hash(“192.168.1.100#1”); 和Hash(“192.168.1.100#2”);。</p>
<h2 id="u603B_u7ED3"><a href="#u603B_u7ED3" class="headerlink" title="总结"></a>总结</h2><p>　　常规的hash算法：对要存储<strong>数据</strong>的key进行hash计算，分配到不同节点存储。<br>　　一致性hash算法：对要存储<strong>数据</strong>的key和<strong>服务器</strong>都进行hash计算，进而确认每个key的存储位置，它是分布式哈希（DHT）实现算法</p>
<p>　　spymemcache的源码采用了一致性hash算法ketama进行数据存储节点的选择</p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2><p><a href="http://blog.csdn.net/hguisu/article/details/6163621" target="_blank" rel="external">http://blog.csdn.net/hguisu/article/details/6163621</a></p>
<p><a href="http://cjjwzs.javaeye.com/blog/762453" target="_blank" rel="external">http://cjjwzs.javaeye.com/blog/762453</a></p>
<p>　　</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/08/cache/3.Cache系列之一致性哈希算法/" data-id="cijzzpvi800ha1cfsr7jdfsj5" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/cache/">cache</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-cache/2.Cache系列之Memcached内存分配机制" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/08/cache/2.Cache系列之Memcached内存分配机制/" class="article-date">
  <time datetime="2016-01-07T18:00:00.000Z" itemprop="datePublished">2016-01-08</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/cache/">cache</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/08/cache/2.Cache系列之Memcached内存分配机制/">Cache系列二之Memcached内存分配机制</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　6、  单个item的大小被限制在1M byte之内<br>因为内存分配器的算法就是这样的。<br>详细的回答：<br>1）Memcached的内存存储引擎，使用slabs来管理内存。内存被分成大小不等的slabs chunks（先分成大小相等的slabs，然后每个slab被分成大小相等chunks，不同slab的chunk大小是不相等的）。chunk的大小依次从一个最小数开始，按某个因子增长，直到达到最大的可能值。如果最小值为400B，最大值是1MB，因子是1.20，各个slab的chunk的大小依次是：<br>slab1 - 400B；slab2 - 480B；slab3 - 576B …slab中chunk越大，它和前面的slab之间的间隙就越大。因此，最大值越大，内存利用率越低。Memcached必须为每个slab预先分配内存，因此如果设置了较小的因子和较大的最大值，会需要为Memcached提供更多的内存。<br>2）不要尝试向memcached中存取很大的数据，例如把巨大的网页放到mencached中。因为将大数据load和unpack到内存中需要花费很长的时间，从而导致系统的性能反而不好。如果确实需要存储大于1MB的数据，可以修改slabs.c：POWER_BLOCK的值，然后重新编译memcached；或者使用低效的malloc/free。另外，可以使用数据库、MogileFS等方案代替Memcached系统。<br>7、  memcached的内存分配器是如何工作的？为什么不适用malloc/free！？为何要使用slabs？<br>实际上，这是一个编译时选项。默认会使用内部的slab分配器，而且确实应该使用内建的slab分配器。最早的时候，memcached只使用malloc/free来管理内存。然而，这种方式不能与OS的内存管理以前很好地工作。反复地malloc/free造成了内存碎片，OS最终花费大量的时间去查找连续的内存块来满足malloc的请求，而不是运行memcached进程。slab分配器就是为了解决这个问题而生的。内存被分配并划分成chunks，一直被重复使用。因为内存被划分成大小不等的slabs，如果item的大小与被选择存放它的slab不是很合适的话，就会浪费一些内存。</p>
<p>10、 memcached的内存分配器是如何工作的？为什么不适用malloc/free！？为何要使用slabs？<br>实际上，这是一个编译时选项。默认会使用内部的slab分配器，而且确实应该使用内建的slab分配器。最早的时候，memcached只使用malloc/free来管理内存。然而，这种方式不能与OS的内存管理以前很好地工作。反复地malloc/free造成了内存碎片，OS最终花费大量的时间去查找连续的内存块来满足malloc的请求，而不是运行memcached进程。slab分配器就是为了解决这个问题而生的。内存被分配并划分成chunks，一直被重复使用。因为内存被划分成大小不等的slabs，如果item的大小与被选择存放它的slab不是很合适的话，就会浪费一些内存。</p>
<p>反复地malloc/free造成了内存碎片，OS最终花费大量时间查找内存块来满足malloc的恳求，而不是运行memcached过程。</p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2><p><a href="http://blog.csdn.net/hguisu/article/details/6163621" target="_blank" rel="external">http://blog.csdn.net/hguisu/article/details/6163621</a></p>
<p><a href="http://cjjwzs.javaeye.com/blog/762453" target="_blank" rel="external">http://cjjwzs.javaeye.com/blog/762453</a></p>
<p>　　</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/08/cache/2.Cache系列之Memcached内存分配机制/" data-id="cijzzpvib00hd1cfs543864sb" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/cache/">cache</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/memecached/">memecached</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-cache/1.Cache系列之Memcached入门" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/08/cache/1.Cache系列之Memcached入门/" class="article-date">
  <time datetime="2016-01-07T17:00:00.000Z" itemprop="datePublished">2016-01-08</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/cache/">cache</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/08/cache/1.Cache系列之Memcached入门/">Cache系列一之Memcached入门</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　Memcached是一个高性能的分布式内存对象缓存系统，通过在内存中缓存数据和对象来减少读取数据库的次数，从而提高性能。Memcached基于一个存储key-value对的hashmap，采用一致性哈希算法，实现数据的分布式缓存。其守护进程（daemon ）是用C写的，但是客户端可以用任何语言来编写，并通过memcached协议与守护进程通信。</p>
<h2 id="u5B89_u88C5"><a href="#u5B89_u88C5" class="headerlink" title="安装"></a>安装</h2><p>　　由于memcached用到了libevent，所以在编译安装memcached之前需要先安装libevent，完整安装命令如下：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#Debian/Ubuntu</span></span><br><span class="line">apt-get install libevent-dev</span><br><span class="line"></span><br><span class="line"><span class="comment">#Redhat/Centos</span></span><br><span class="line">yum install libevent-devel</span><br><span class="line">				</span><br><span class="line">tar -zxvf memcached-<span class="number">1</span>.x.x.tar.gz</span><br><span class="line"><span class="built_in">cd</span> memcached-<span class="number">1</span>.x.x</span><br><span class="line">./configure &amp;&amp; make &amp;&amp; make <span class="built_in">test</span> &amp;&amp; sudo make install</span><br><span class="line"></span><br><span class="line"><span class="comment">#启动</span></span><br><span class="line">memcached <span class="operator">-d</span> -m <span class="number">10</span> -u root <span class="operator">-l</span> <span class="number">192.168</span>.<span class="number">0.200</span> -p <span class="number">12000</span> -c <span class="number">256</span> -P /tmp/memcached.pid</span><br><span class="line"><span class="comment">#-d选项是启动一个守护进程</span></span><br><span class="line"><span class="comment">#-m是分配给Memcache使用的内存数量，单位是MB，我这里是10MB</span></span><br><span class="line"><span class="comment">#-u是运行Memcache的用户，我这里是root</span></span><br><span class="line"><span class="comment">#-l是监听的服务器IP地址，如果有多个地址的话，我这里指定了服务器的IP地址192.168.0.200</span></span><br><span class="line"><span class="comment">#-p是设置Memcache监听的端口，我这里设置了12000，最好是1024以上的端口</span></span><br><span class="line"><span class="comment">#-c选项是最大运行的并发连接数，默认是1024，我这里设置了256，按照你服务器的负载量来设定</span></span><br><span class="line"><span class="comment">#-P是设置保存Memcache的pid文件，我这里是保存在 /tmp/memcached.pid</span></span><br><span class="line"></span><br><span class="line"><span class="comment">#结束Memcache进程</span></span><br><span class="line"><span class="built_in">kill</span> <span class="string">'cat /tmp/memcached.pid'</span></span><br></pre></td></tr></table></figure></p>
<h2 id="u7279_u6027"><a href="#u7279_u6027" class="headerlink" title="特性"></a>特性</h2><p>　　1.  原子操作：所有被发送到memcached的单个命令被串行化，先后执行。注意：如果首先通过get命令获取了一个item，修改了它，然后再把它set回memcached，系统不保证这个item没有被其他进程操作过。但是 memcached1.2.5 以及更高版本，提供了gets和cas命令来解决这个问题。gets命令会返回key的当前值的唯一标识。而cas命令把该唯一标识和该key的新值一起发送给memcached。如果该item存放在memcached中的唯一标识与您提供的一致，写操作将会成功。如果另一个进程在这期间也修改了这个item，那么该item存放在memcached中的唯一标识将会改变，写操作就会失败<br>　　2. 二进制协议：尝试为端提供一个更有效的、可靠的协议，减少客户端/服务器端因处理协议而产生的CPU时间。根据Facebook的测试，解析ASCII协议是memcached中消耗CPU时间最多的环节。<a href="http://code.google.com/p/memcached/wiki/MemcacheBinaryProtocol" target="_blank" rel="external">http://code.google.com/p/memcached/wiki/MemcacheBinaryProtocol</a><br>　　3. memcached节点不相互通信，不会产生广播风暴，不会因为集群规模增大而增加memcached负担，所以非常容易的扩充memcached缓存。<br>　　4. 未实现冗余和容错机制<br>　　5. 淘汰机制是LRU算法 + 超时失效。当您存数据到memcached中，可以指定该数据在缓存中可以呆多久Which is forever， or some time in the future。若是memcached的内存不敷用了，过期的slabs会优先被调换，接着就轮到最老的未被应用的slabs。</p>
<h2 id="u5E94_u7528_u573A_u666F"><a href="#u5E94_u7528_u573A_u666F" class="headerlink" title="应用场景"></a>应用场景</h2><p>　　1. 缓存一些很小但是被频繁访问的数据或文件<br>　　2. 缓存session数据或者临时数据</p>
<h2 id="u9650_u5236"><a href="#u9650_u5236" class="headerlink" title="限制"></a>限制</h2><p>　　1. 存储单个item最大数据是在1MB内（默认编译下受限于其内存分配器算法），如果数据超过1M,存取set和get是都是返回false，而且引起性能的问题。memcached server不能存储超过1M的数据，但是经过客户端压缩数据后，只要小于1M的数据都能存储成功，所以memcached set数据的时候如果支持在客户端压缩，也是可以解决问题的，或者将数据在客户端拆分到多个key中。<br>　　2. key的长度大于250字符，250是memcached服务器端内部的限制。如果使用的Memcached客户端支持”key的前缀”或类似特性，那么key（前缀+原始key）的最大长度是可以超过250个字符的。<br>　　3. 不适合运行在虚拟主机不。Memcached需要接管和控制大块的内存，如果memcached管理的内存被OS或 hypervisor交换出去，memcached的性能将大打折扣。<br>　　4. Memcached未提供任何安全策略，仅仅通过telnet就可以访问到memcached。如果应用运行在共享的系统上，需要着重考虑安全问题，可以考虑防火墙。<br>　　5. 纯内存缓存系统，如需持久化，需要与持久化系统配合使用<br>　　6. Memcached是一个非梗阻的办事器，<strong>不能够遍历memcached中所有的item</strong>。memcached所有的命令，例如add、set、get和fulsh等，无论memcached中存储了多少数据，它们的执行都只消耗常量时间。任何遍历所有item的命令执行所消耗的时间，将随着memcached中数据量的增加而增加。当其他命令因为等待（遍历所有item的命令执行完毕）而不能得到执行，因而阻塞将发生。所以遍历功能不适合其设计初衷<br>　　7. 默认情况下最大30天过期，memcached把传入的过期时候（时间段）转换成过期时间点后，一旦到了这个时间点，memcached就把item置为失效状况。注意：在内存达到使用限制后它也会回收最少使用的数据（实际上并未过期）。因此，如果我们要把它当作static变量的话就要考虑到这个问题，必须有重新初始化数据的过程。其实应该这么想，既然是缓存就是拿到了存起来。如果没有，则必定有一个重新获取重新缓存的过程，而不是想着它永远存在。</p>
<h2 id="redis_u3001memecached_u6BD4_u8F83"><a href="#redis_u3001memecached_u6BD4_u8F83" class="headerlink" title="redis、memecached比较"></a>redis、memecached比较</h2><table>
<thead>
<tr>
<th style="text-align:center">缓存</th>
<th style="text-align:center">持久化</th>
<th style="text-align:center">数据结构</th>
<th style="text-align:center">集群</th>
<th style="text-align:center">其他</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">redis</td>
<td style="text-align:center">支持</td>
<td style="text-align:center">string、set、list、hash和Sorted Set</td>
<td style="text-align:center">客户端实现一致性哈希<br>服务端实现master-slave和sentinel</td>
<td style="text-align:center">发布-订阅功能</td>
</tr>
<tr>
<td style="text-align:center">memcached</td>
<td style="text-align:center">不支持</td>
<td style="text-align:center">key-value</td>
<td style="text-align:center">客户端实现一致性哈希</td>
<td style="text-align:center">内存预分配机制</td>
</tr>
</tbody>
</table>
<p>　　mysql的query cache主动地缓存SQL查询的成果（是语句级别的），被缓存的SQL查询可以被反复地快速执行。它以集中式的管理方式，使连接到该query cache的MySQL办事器都会收益。当修改表时，query cache会立即被刷新（flush），当写操作频繁时，其缓存数据可能都会失效。</p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2><p><a href="http://blog.csdn.net/hguisu/article/details/6163621" target="_blank" rel="external">http://blog.csdn.net/hguisu/article/details/6163621</a></p>
<p>　　</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/08/cache/1.Cache系列之Memcached入门/" data-id="cijzzpuxm00001cfs6gh4kedm" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/cache/">cache</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/memecached/">memecached</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-database/1.移动终端的空间查询" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/08/database/1.移动终端的空间查询/" class="article-date">
  <time datetime="2016-01-07T17:00:00.000Z" itemprop="datePublished">2016-01-08</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/database/">database</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/08/database/1.移动终端的空间查询/">移动终端的空间查询</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　大约一年前在andorid移动端做离线空间数据查询，束手无策之际发现了spatialite for android，试用了下，效果还不错，现在只记得需要在linux服务器上编译好动态库。忘了当时怎么做了，有时间补上！</p>
<h2 id="u53C2_u8003_u94FE_u63A5"><a href="#u53C2_u8003_u94FE_u63A5" class="headerlink" title="参考链接"></a>参考链接</h2><p><a href="http://www.gaia-gis.it/spatialite-2.4.0-4/splite-jdbc.html" target="_blank" rel="external">http://www.gaia-gis.it/spatialite-2.4.0-4/splite-jdbc.html</a><br><a href="http://www.gaia-gis.it/gaia-sins/spatialite-cookbook/html/java.html" target="_blank" rel="external">http://www.gaia-gis.it/gaia-sins/spatialite-cookbook/html/java.html</a><br><a href="http://www.gaia-gis.it/gaia-sins/spatialite-tutorial-2.3.1.html" target="_blank" rel="external">http://www.gaia-gis.it/gaia-sins/spatialite-tutorial-2.3.1.html</a><br><a href="http://www.cnblogs.com/mapzone/articles/2380983.html" target="_blank" rel="external">http://www.cnblogs.com/mapzone/articles/2380983.html</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/08/database/1.移动终端的空间查询/" data-id="cijzzpvi400h61cfsiu2sazyb" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/spatialite-for-android/">spatialite for android</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-mq/3.RabbitMQ系列之转发器" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/07/mq/3.RabbitMQ系列之转发器/" class="article-date">
  <time datetime="2016-01-06T19:00:00.000Z" itemprop="datePublished">2016-01-07</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/mq/">mq</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/07/mq/3.RabbitMQ系列之转发器/">RabbitMQ系列三之转发器</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　上一篇博客中我们实现的队列中的消息只会转发给一个消费者，在这篇文章中，我们将实现把一个消息发给多个消费者，这种模式称之为发布/订阅（类似观察者模式）。<br>　　为验证这种模式，实现该功能，我们需要引入转发器的概念。</p>
<h2 id="u8F6C_u53D1_u5668_uFF08Exchanges_uFF09"><a href="#u8F6C_u53D1_u5668_uFF08Exchanges_uFF09" class="headerlink" title="转发器（Exchanges）"></a>转发器（Exchanges）</h2><p>　　之前我们实现的是<strong>发送者发送消息给队列，接收者从队列接收消息</strong>。事实上，   RabbitMQ消息模型的核心理念是<strong>生产者永远不会直接发送任何消息给队列</strong>，生产者甚至不知道消息应该发送到哪些队列。相反的，生产者只能发送消息给转发器（Exchange）。转发器一边接收从生产者发来的消息，另一边把消息推送到一个或多个队列中，也有可能丢弃该消息）。<br>　　Rabbitmq为我们提供的转发器有：Direct、Topic、Headers和Fanout。它们的区别如下：<br>　　1. fanout：所有bind到此exchange的queue都可以接收消息<br>　　2. direct：通过routingKey和exchange决定哪个queue可以接收消息。如果有多个queue都完全匹配，这这些queue都会收到消息<br>　　3. topic：所有符合routingKey(此时可以是一个表达式)的routingKey所bind的queue可以接收消息。其中#代表一个或多个字符，*代表任何字符。例如：#.a会匹配a.a，aa.a，aaa.a等，*.a会匹配a.a，b.a，c.a等。注：使用RoutingKey为#，Exchange Type为topic的时候相当于使用fanout<br>　　4. headers：rabbitmq中每条消息都有消息头，生产者发送消息时需要在headers中写入值，消费者中绑定队列时需要指定匹配的headers属性值。</p>
<h2 id="Fanout_u8F6C_u53D1_u5668"><a href="#Fanout_u8F6C_u53D1_u5668" class="headerlink" title="Fanout转发器"></a>Fanout转发器</h2><p>　　Fanout转发器负责把它接受到的消息，广播到所有它知道的队列中。这里我们先实现一个日志生产者，它负责将日志发送到名为ex_log的转发器中，实现代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LogProducer</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"ex_log"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明转发器和类型</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"fanout"</span>);</span><br><span class="line"></span><br><span class="line">        String message = <span class="keyword">new</span> Date().toLocaleString()+<span class="string">" : log something"</span>;</span><br><span class="line">        <span class="comment">// 往转发器上发送消息 exchange routeKey props data</span></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">""</span>, <span class="keyword">null</span>, message.getBytes());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">" [x] Sent '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭频道和资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　接下来，我们实现两个消费者，一个负责打印日志，一个负责写入日志到磁盘文件中。注意，每个消费者都声明了各自的队列，并将队列绑定到了名为ex_log的转发器上，如下所示：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//消费者一</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintConsumer</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"ex_log"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> java.io.IOException,</span><br><span class="line">            java.lang.InterruptedException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"fanout"</span>);</span><br><span class="line">        <span class="comment">// 创建一个非持久的、唯一的且自动删除的队列</span></span><br><span class="line">        String queueName = channel.queueDeclare().getQueue();</span><br><span class="line">        <span class="comment">// 为转发器指定队列，queue exchange routeKey</span></span><br><span class="line">        <span class="comment">//第三个参数可以填任意值</span></span><br><span class="line">        channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">""</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        QueueingConsumer consumer = <span class="keyword">new</span> QueueingConsumer(channel);</span><br><span class="line">        <span class="comment">// 指定接收者，第二个参数为自动应答，无需手动应答</span></span><br><span class="line">        channel.basicConsume(queueName, <span class="keyword">true</span>, consumer);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>)</span><br><span class="line">        &#123;</span><br><span class="line">            QueueingConsumer.Delivery delivery = consumer.nextDelivery();</span><br><span class="line">            String message = <span class="keyword">new</span> String(delivery.getBody());</span><br><span class="line">            System.out.println(<span class="string">" [x] Received '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//消费者二</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SaveConsumer</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"ex_log"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> java.io.IOException,</span><br><span class="line">            InterruptedException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line"></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"fanout"</span>);</span><br><span class="line">        <span class="comment">// 创建一个非持久的、唯一的且自动删除的队列</span></span><br><span class="line">        String queueName = channel.queueDeclare().getQueue();</span><br><span class="line">        <span class="comment">// 将队列绑定到转发器上 queue exchange routeKey</span></span><br><span class="line">        <span class="comment">//第三个参数可以填任意值，无需与PrintConsumer的保持一致</span></span><br><span class="line">        channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">""</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        QueueingConsumer consumer = <span class="keyword">new</span> QueueingConsumer(channel);</span><br><span class="line">        <span class="comment">// 指定接收者，第二个参数为自动应答，无需手动应答</span></span><br><span class="line">        channel.basicConsume(queueName, <span class="keyword">true</span>, consumer);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            QueueingConsumer.Delivery delivery = consumer.nextDelivery();</span><br><span class="line">            String message = <span class="keyword">new</span> String(delivery.getBody());</span><br><span class="line">            print2File(message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">print2File</span><span class="params">(String msg)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            String dir = SaveConsumer.class.getClassLoader().getResource(<span class="string">""</span>).getPath();</span><br><span class="line">            String logFileName = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd"</span>).format(<span class="keyword">new</span> Date());</span><br><span class="line">            File file = <span class="keyword">new</span> File(dir, logFileName + <span class="string">".txt"</span>);</span><br><span class="line">            FileOutputStream fos = <span class="keyword">new</span> FileOutputStream(file, <span class="keyword">true</span>);</span><br><span class="line">            fos.write((msg + <span class="string">"\r\n"</span>).getBytes());</span><br><span class="line">            fos.flush();</span><br><span class="line">            fos.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="Direct_u8F6C_u53D1_u5668"><a href="#Direct_u8F6C_u53D1_u5668" class="headerlink" title="Direct转发器"></a>Direct转发器</h2><p>　　为演示Direct转发器的功能，这里我们定义了一个名为directExchange的direct转发器和两个名称分别为routeKey1和routeKey2的routeKey。生产者向directExchange-routeKey1发送了两条消息，向directExchange-routeKey2发送了一条消息。实现代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//生产者</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LogProducer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"directExchange"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明转发器和类型</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"direct"</span>);</span><br><span class="line"></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">"routeKey1"</span>,</span><br><span class="line">                MessageProperties.PERSISTENT_TEXT_PLAIN, <span class="string">"hello world1"</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">"routeKey1"</span>,</span><br><span class="line">                MessageProperties.PERSISTENT_TEXT_PLAIN, <span class="string">"hello world2"</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">"routeKey2"</span>,</span><br><span class="line">                MessageProperties.PERSISTENT_TEXT_PLAIN, <span class="string">"hello world3"</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭频道和资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//消费者一</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintConsumer1</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"directExchange"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> java.io.IOException,</span><br><span class="line">            InterruptedException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"direct"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建一个非持久的、唯一的且自动删除的队列</span></span><br><span class="line">        String queueName = channel.queueDeclare().getQueue();</span><br><span class="line">        <span class="comment">// 为转发器指定队列， queue exchange routeKey</span></span><br><span class="line">        channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">"routeKey1"</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        QueueingConsumer consumer = <span class="keyword">new</span> QueueingConsumer(channel);</span><br><span class="line">        <span class="comment">// 指定接收者，第二个参数为自动应答，无需手动应答</span></span><br><span class="line">        channel.basicConsume(queueName, <span class="keyword">true</span>, consumer);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            QueueingConsumer.Delivery delivery = consumer.nextDelivery();</span><br><span class="line">            String message = <span class="keyword">new</span> String(delivery.getBody());</span><br><span class="line">            System.out.println(<span class="string">" [x] Received '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//消费者PrintConsumer2的实现与PrintConsumer1唯一不同的就是：</span></span><br><span class="line">channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">"routeKey2"</span>);</span><br></pre></td></tr></table></figure></p>
<p>　　运行程序即可看到预期的结果，这里不在赘述！</p>
<h2 id="Topic_u8F6C_u53D1_u5668"><a href="#Topic_u8F6C_u53D1_u5668" class="headerlink" title="Topic转发器"></a>Topic转发器</h2><p>　　为演示Topic转发器的功能，这里我们定义了一个名为directExchange的topic转发器和两个名称分别为test1.<em>和test2.</em>的routeKey。生产者向directExchange-test1.aa发送了两条消息，向directExchange-test2.bb发送了一条消息。实现代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//生产者</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LogProducer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"topicExchange"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明转发器和类型</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"topic"</span>);</span><br><span class="line"></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">"test1.aa"</span>,</span><br><span class="line">                MessageProperties.PERSISTENT_TEXT_PLAIN, <span class="string">"hello world1"</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">"test1.aa"</span>,</span><br><span class="line">                MessageProperties.PERSISTENT_TEXT_PLAIN, <span class="string">"hello world2"</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">"test2.bb"</span>,</span><br><span class="line">                MessageProperties.PERSISTENT_TEXT_PLAIN, <span class="string">"hello world3"</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭频道和资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//消费者一</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintConsumer1</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"topicExchange"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> java.io.IOException,</span><br><span class="line">            InterruptedException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"topic"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建一个非持久的、唯一的且自动删除的队列</span></span><br><span class="line">        String queueName = channel.queueDeclare().getQueue();</span><br><span class="line">        <span class="comment">// 为转发器指定队列， queue exchange routeKey</span></span><br><span class="line">        channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">"test1.*"</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        QueueingConsumer consumer = <span class="keyword">new</span> QueueingConsumer(channel);</span><br><span class="line">        <span class="comment">// 指定接收者，第二个参数为自动应答，无需手动应答</span></span><br><span class="line">        channel.basicConsume(queueName, <span class="keyword">true</span>, consumer);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            QueueingConsumer.Delivery delivery = consumer.nextDelivery();</span><br><span class="line">            String message = <span class="keyword">new</span> String(delivery.getBody());</span><br><span class="line">            System.out.println(<span class="string">" [x] Received '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//PrintConsumer2与PrintConsumer1唯一不同之处在于：</span></span><br><span class="line">channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">"test2.*"</span>);</span><br></pre></td></tr></table></figure></p>
<h2 id="Headers_u8F6C_u53D1_u5668"><a href="#Headers_u8F6C_u53D1_u5668" class="headerlink" title="Headers转发器"></a>Headers转发器</h2><p>　　在rabbitmq中，每条消息都可以附带一些属性，Headers转发器就是根据消息中属性的值决定将消息发送到哪个队列中。<br>　　生产者发送了三条消息，其中两条含有属性key1=value1，一条含有属性key1=value1，key2=value2。<br>　　一个消费者匹配属性中含有key1=value1或key2=value2（或者两个同时存在）。另一个消费者匹配key1=value1和key2=value2同时存在的消息。代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LogProducer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"headersExchange"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明转发器和类型</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"headers"</span>);</span><br><span class="line"></span><br><span class="line">        AMQP.BasicProperties.Builder builder1 = <span class="keyword">new</span> AMQP.BasicProperties.Builder();</span><br><span class="line">        Map&lt;String,Object&gt; map1 = <span class="keyword">new</span> HashMap&lt;String, Object&gt;();</span><br><span class="line">        map1.put(<span class="string">"key1"</span>, <span class="string">"value1"</span>);</span><br><span class="line">        AMQP.BasicProperties properties1 = builder1.headers(map1).build();</span><br><span class="line"></span><br><span class="line">        AMQP.BasicProperties.Builder builder2 = <span class="keyword">new</span> AMQP.BasicProperties.Builder();</span><br><span class="line">        Map&lt;String,Object&gt; map2 = <span class="keyword">new</span> HashMap&lt;String, Object&gt;();</span><br><span class="line">        map2.put(<span class="string">"key1"</span>, <span class="string">"value1"</span>);</span><br><span class="line">        map2.put(<span class="string">"key2"</span>, <span class="string">"value2"</span>);</span><br><span class="line">        AMQP.BasicProperties properties2 = builder2.headers(map2).build();</span><br><span class="line"></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">""</span>,</span><br><span class="line">                properties1, <span class="string">"hello world1"</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">""</span>,</span><br><span class="line">                properties1, <span class="string">"hello world2"</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">""</span>,</span><br><span class="line">                properties2, <span class="string">"hello world3"</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭频道和资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintConsumer1</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"headersExchange"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> java.io.IOException,</span><br><span class="line">            InterruptedException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"headers"</span>);</span><br><span class="line"></span><br><span class="line">        String queueName = channel.queueDeclare().getQueue();</span><br><span class="line">        <span class="comment">// 为转发器指定队列， queue exchange routeKey</span></span><br><span class="line">        channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">""</span>);</span><br><span class="line"></span><br><span class="line">        Map&lt;String, Object&gt; map = <span class="keyword">new</span> HashMap&lt;String, Object&gt;();</span><br><span class="line">        map.put(<span class="string">"x-match"</span>, <span class="string">"any"</span>);</span><br><span class="line">        map.put(<span class="string">"key1"</span>, <span class="string">"value1"</span>);</span><br><span class="line">        map.put(<span class="string">"key2"</span>, <span class="string">"value2"</span>);</span><br><span class="line">        channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">""</span>, map);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        QueueingConsumer consumer = <span class="keyword">new</span> QueueingConsumer(channel);</span><br><span class="line">        <span class="comment">// 指定接收者，第二个参数为自动应答，无需手动应答</span></span><br><span class="line">        channel.basicConsume(queueName, <span class="keyword">true</span>, consumer);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            QueueingConsumer.Delivery delivery = consumer.nextDelivery();</span><br><span class="line">            String message = <span class="keyword">new</span> String(delivery.getBody());</span><br><span class="line">            System.out.println(<span class="string">" [x] Received '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintConsumer2</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">"headersExchange"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> java.io.IOException,</span><br><span class="line">            InterruptedException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">"headers"</span>);</span><br><span class="line"></span><br><span class="line">        String queueName = channel.queueDeclare().getQueue();</span><br><span class="line">        Map&lt;String, Object&gt; map = <span class="keyword">new</span> HashMap&lt;String, Object&gt;();</span><br><span class="line">        map.put(<span class="string">"x-match"</span>, <span class="string">"all"</span>);</span><br><span class="line">        map.put(<span class="string">"key1"</span>, <span class="string">"value1"</span>);</span><br><span class="line">        map.put(<span class="string">"key2"</span>, <span class="string">"value2"</span>);</span><br><span class="line">        channel.queueBind(queueName, EXCHANGE_NAME, <span class="string">""</span>, map);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        QueueingConsumer consumer = <span class="keyword">new</span> QueueingConsumer(channel);</span><br><span class="line">        <span class="comment">// 指定接收者，第二个参数为自动应答，无需手动应答</span></span><br><span class="line">        channel.basicConsume(queueName, <span class="keyword">true</span>, consumer);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            QueueingConsumer.Delivery delivery = consumer.nextDelivery();</span><br><span class="line">            String message = <span class="keyword">new</span> String(delivery.getBody());</span><br><span class="line">            System.out.println(<span class="string">" [x] Received '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　示例代码：<a href="/code/rabbitmq-exchange.zip">rabbitmq-exchange.zip</a></p>
<h2 id="u53C2_u8003_u5730_u5740"><a href="#u53C2_u8003_u5730_u5740" class="headerlink" title="参考地址"></a>参考地址</h2><p><a href="http://blog.csdn.net/lmj623565791/article/details/37657225" target="_blank" rel="external">http://blog.csdn.net/lmj623565791/article/details/37657225</a><br><a href="http://melin.iteye.com/blog/691265" target="_blank" rel="external">http://melin.iteye.com/blog/691265</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/07/mq/3.RabbitMQ系列之转发器/" data-id="cijzzpv9q008j1cfs316502wa" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mq/">mq</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/rabbitmq/">rabbitmq</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-mq/2.RabbitMQ系列之工作队列" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/07/mq/2.RabbitMQ系列之工作队列/" class="article-date">
  <time datetime="2016-01-06T18:00:00.000Z" itemprop="datePublished">2016-01-07</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/mq/">mq</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/07/mq/2.RabbitMQ系列之工作队列/">RabbitMQ系列二之工作队列</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　工作队列的主要任务是：避免立刻执行资源密集型任务，并等待其完成。相反地，我们进行任务调度，把任务封装为消息发送给队列，程序在后台运行并不断的从队列中取出任务然后执行。这样的概念在web应用中极其有用，当在很短的HTTP请求间需要执行复杂的任务。</p>
<h2 id="u51C6_u5907"><a href="#u51C6_u5907" class="headerlink" title="准备"></a>准备</h2><p>　　我们使用Thread.sleep来模拟耗时的任务。我们在发送到队列的消息的末尾添加一定数量的点，每个点代表在工作线程中需要耗时1秒，例如hello…将会需要等待3秒。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Producer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">"workqueue"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">//声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        <span class="comment">//发送10条消息，依次在消息后面附加1-10个点</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">            String dots = <span class="string">""</span>;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt;= i; j++) &#123;</span><br><span class="line">                dots += <span class="string">"."</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            String message = <span class="string">"helloworld"</span> + dots + dots.length();</span><br><span class="line">            <span class="comment">//exchange, routingKey, props, body</span></span><br><span class="line">            channel.basicPublish(<span class="string">""</span>, QUEUE_NAME, <span class="keyword">null</span>, message.getBytes());</span><br><span class="line">            System.out.println(<span class="string">" [x] Sent '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//关闭频道和资源</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　消费者<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Consumer</span> </span>&#123;</span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">"workqueue"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> java.io.IOException,</span><br><span class="line">            java.lang.InterruptedException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">//区分不同工作进程的输出</span></span><br><span class="line">        <span class="keyword">int</span> hashCode = Consumer.class.hashCode();</span><br><span class="line">        <span class="comment">//创建连接和频道</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">//声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        System.out.println(hashCode + <span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        QueueingConsumer consumer = <span class="keyword">new</span> QueueingConsumer(channel);</span><br><span class="line">        <span class="comment">// 指定消费队列</span></span><br><span class="line">        <span class="comment">//queue, autoAck, callback</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">true</span>, consumer);</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            QueueingConsumer.Delivery delivery = consumer.nextDelivery();</span><br><span class="line">            String message = <span class="keyword">new</span> String(delivery.getBody());</span><br><span class="line"></span><br><span class="line">            System.out.println(hashCode + <span class="string">" [x] Received '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">            doWork(message);</span><br><span class="line">            System.out.println(hashCode + <span class="string">" [x] Done"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span><br><span class="line">     * 每个点耗时1s</span><br><span class="line">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">doWork</span><span class="params">(String task)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">char</span> ch : task.toCharArray()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (ch == <span class="string">'.'</span>)</span><br><span class="line">                Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>　　使用任务队列的好处是能够很容易的并行工作。如果我们积压了很多工作，我们仅仅通过增加更多的工作者就可以解决问题，使系统的伸缩性更加容易。<br>　　下面我们先<strong>运行3个消费者</strong>（Consumer.java）实例，然后运行Producer.java，发送10条消息。此时3个消费者实例都会得到信息。但是如何分配呢？让我们来看输出结果：<br>客户端一：<br>1318484115 [*] Waiting for messages. To exit press CTRL+C<br>1318484115 [x] Received ‘helloworld.1’<br>1318484115 [x] Done<br>1318484115 [x] Received ‘helloworld….4’<br>1318484115 [x] Done<br>1318484115 [x] Received ‘helloworld…….7’<br>1318484115 [x] Done<br>1318484115 [x] Received ‘helloworld……….10’<br>1318484115 [x] Done</p>
<p>客户端二：<br>1318484115 [*] Waiting for messages. To exit press CTRL+C<br>1318484115 [x] Received ‘helloworld..2’<br>1318484115 [x] Done<br>1318484115 [x] Received ‘helloworld…..5’<br>1318484115 [x] Done<br>1318484115 [x] Received ‘helloworld……..8’<br>1318484115 [x] Done</p>
<p>客户端三：<br>2026251059 [*] Waiting for messages. To exit press CTRL+C<br>2026251059 [x] Received ‘helloworld…3’<br>2026251059 [x] Done<br>2026251059 [x] Received ‘helloworld……6’<br>2026251059 [x] Done<br>2026251059 [x] Received ‘helloworld………9’<br>2026251059 [x] Done</p>
<p>　　可以看到，RabbitMQ默认会一个一个的发送信息给下一个消费者(consumer)，而不考虑每个任务的时长等等，且是一次性分配，并非一个一个分配。每个消费者将会获得相等数量的消息，这样分发消息的方式叫做<strong>round-robin</strong>。<br>　　如果先启动一个consumer，接着马上启动producer，最后再启动两个consumer。此时，即使第一个Work只处理了两个消息，后启动的另外两个Work也不会处理任何消息，全部由第一个Work处理，说明是一次性分配。<strong>*待三个都启动后，再启动producer，此时会平均分配到三个consumer</strong></p>
<h2 id="u6D88_u606F_u5E94_u7B54"><a href="#u6D88_u606F_u5E94_u7B54" class="headerlink" title="消息应答"></a>消息应答</h2><p>　　三个消费者都在运行，会立刻收到消息并应答，RabbItMQ收到应答后会从内存中移除这个信息。由于每次消费一条消息都会阻塞一段时间（实际已接收到所有消息），如果杀死正在执行任务的某个消费者，会丢失它还未处理的消息。RabbItMQ也不会转发给其他的消费者（已经收到消费者的应答）。<br>　　当某个消费者被杀死时，我们希望将任务传递给另一个消费者，保证消息永远不会丢失，为此RabbitMQ提供了消息应答（message acknowledgments）机制。消费者发送应答给RabbitMQ，告诉它信息已经被接收和处理，然后RabbitMQ可以自由的进行信息删除。<br>　　如果消费者被杀死而没有发送应答，RabbitMQ会认为该信息没有被完全的处理，然后将会重新转发给别的消费者。通过这种方式，可以确认信息不会被丢失，即使消费者被杀死。这种机制并没有超时时间这么一说，<strong>RabbitMQ会在消费者连接断开时重新转发此信息</strong>。如果消费者处理一个信息需要耗费特别长的时间是允许的。<br>　　消息应答默认是打开的，只需修改Consumer中的代码<strong>channel.basicConsume(QUEUE_NAME, false, consumer);</strong>的第二个参数为false，并在doWork方法后增加一行代码：<strong>channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);</strong>即可。这样就完成了手动应答的过程，完整代码请参见后面示例代码中的ConsumerAck.java</p>
<h2 id="u6D88_u606F_u6301_u4E45_u5316"><a href="#u6D88_u606F_u6301_u4E45_u5316" class="headerlink" title="消息持久化"></a>消息持久化</h2><p>　　当RabbitMQ服务被停止或异常退出时，队列和消息仍然会丢失。如果要确保信息不会被丢失，我们需要给所有的队列和消息设置持久化的标志。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//队列声明为持久化的：</span></span><br><span class="line"><span class="keyword">boolean</span> durable = <span class="keyword">true</span>;</span><br><span class="line">channel.queueDeclare(<span class="string">"task_queue"</span>, durable, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line"><span class="comment">//注：RabbitMQ不允许使用不同的参数重新定义一个队列，所以已经存在的队列，我们无法修改其属性。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//标识消息为持久化的，通过设置MessageProperties（implements BasicProperties）值为PERSISTENT_TEXT_PLAIN即可</span></span><br><span class="line">channel.basicPublish(<span class="string">""</span>, <span class="string">"task_queue"</span>,MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());</span><br></pre></td></tr></table></figure></p>
<h2 id="u516C_u5E73_u8F6C_u53D1"><a href="#u516C_u5E73_u8F6C_u53D1" class="headerlink" title="公平转发"></a>公平转发</h2><p>　　目前的消息转发机制（Round-robin）存在一个问题，假设对于两个消费者，有一系列的任务，奇数任务特别耗时，而偶数任务却很轻松，这样造成一个消费者一直繁忙，另一个消费者却很快执行完任务后等待。<br>　　这是因为当消息到达队列时RabbitMQ就进行转发，并不在乎消费者还有多少任务并未传递应答给RabbitMQ。为了解决这样的问题，我们可以<strong>使用Channel的basicQos方法</strong>，传递参数为prefetchCount = 1。这样告诉RabbitMQ不要在同一时间给一个消费者超过一条消息。换句话说，只有在消费者空闲的时候会发送下一条信息。注意：如果所有的工作者都处于繁忙状态，你的队列有可能被填充满。完整代码请参见后面示例代码中的ConsumerQos<br>　　这种模式支持动态增加消费者，因为消息并没有发送出去，动态增加的消费者马上投入工作。而默认的转发机制会造成，即使动态增加了消费者，此时的消息已经分配完毕，即使有很多未完成的任务，无法立即加入工作。</p>
<p>　　示例代码：<a href="/code/rabbitmq-demo2.zip">rabbitmq-demo2.zip</a></p>
<h2 id="u53C2_u8003_u5730_u5740"><a href="#u53C2_u8003_u5730_u5740" class="headerlink" title="参考地址"></a>参考地址</h2><p><a href="http://blog.csdn.net/lmj623565791/article/details/37620057" target="_blank" rel="external">http://blog.csdn.net/lmj623565791/article/details/37620057</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/07/mq/2.RabbitMQ系列之工作队列/" data-id="cijzzpv9u008o1cfseqcxoj0e" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mq/">mq</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/rabbitmq/">rabbitmq</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-mq/1.RabbitMQ系列之入门" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/07/mq/1.RabbitMQ系列之入门/" class="article-date">
  <time datetime="2016-01-06T17:00:00.000Z" itemprop="datePublished">2016-01-07</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/mq/">mq</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/07/mq/1.RabbitMQ系列之入门/">RabbitMQ系列一之入门</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　AMQP，即Advanced Message Queuing Protocol，高级消息队列协议，是应用层协议的一个开放标准，为面向消息的中间件设计。消息中间件主要用于组件之间的解耦，消息的发送者无需知道消息使用者的存在，反之亦然。AMQP的主要特征是面向消息、队列、路由（包括点对点和发布/订阅）、可靠性、安全。<br>　　RabbitMQ是一个开源的AMQP实现，服务器端用Erlang语言编写，支持多种客户端，如：Python、Ruby、.NET、Java、JMS、C、PHP、ActionScript、XMPP、STOMP等，支持AJAX。用于在分布式系统中存储转发消息，在易用性、扩展性、高可用性等方面表现不俗。</p>
<h2 id="Windows_u4E0B_u5B89_u88C5"><a href="#Windows_u4E0B_u5B89_u88C5" class="headerlink" title="Windows下安装"></a>Windows下安装</h2><p>　　先安装erlang(<a href="http://www.erlang.org/download/otp_win32_R15B.exe" target="_blank" rel="external">otp_win32_R15B.exe</a>)，再安装rabbitmq(<a href="http://www.rabbitmq.com/releases/rabbitmq-server/v3.3.4/rabbitmq-server-3.3.4.exe" target="_blank" rel="external">rabbitmq-server-3.3.4.exe</a>)。安装完成后，在RabbitMQ安装目录的sbin目录下会有rabbitmq-server.bat脚本启动服务，安装时可以将rabbit注册为系统服务。</p>
<h2 id="Linux_u4E0B_u5B89_u88C5"><a href="#Linux_u4E0B_u5B89_u88C5" class="headerlink" title="Linux下安装"></a>Linux下安装</h2><p>　　待补充</p>
<h2 id="Web_u7BA1_u7406_u914D_u7F6E"><a href="#Web_u7BA1_u7406_u914D_u7F6E" class="headerlink" title="Web管理配置"></a>Web管理配置</h2><p>　　在DOS下面，进入安装目录（C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-3.4.3\sbin）执行如下命令就可以成功安装。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rabbitmq-plugins <span class="built_in">enable</span> rabbitmq_management</span><br></pre></td></tr></table></figure></p>
<p>　　可以通过访问<a href="http://localhost:15672" target="_blank" rel="external">http://localhost:15672</a>进行测试，默认的登陆账号为：guest，密码为：guest。<br>　　注意：出于安全的考虑，guest这个默认的用户只能通过<a href="http://localhost:15672" target="_blank" rel="external">http://localhost:15672</a>来登录，不能使用IP地址登录，也就是不能远程访问，这对于服务器上没有安装桌面的情况是无法管理维护的。通过IP访问本机上的也不行，必须要用localhost。</p>
<h2 id="u5E38_u7528_u672F_u8BED"><a href="#u5E38_u7528_u672F_u8BED" class="headerlink" title="常用术语"></a>常用术语</h2><p>　　RabbitMQ是信息传输的中间者。本质上，他从生产者（producers）接收消息，转发这些消息给消费者（consumers）。换句话说，他能够根据你指定的规则进行消息转发、缓冲、和持久化，RabbitMQ 的一些常见的术语：<br>　　1. Producing：一个发送消息的程序是一个producer(生产者)。<br>　　2. Queue：队列，依存于RabbitMQ内部。虽然消息通过RabbitMQ在你的应用中传递，但是它们只能存储在queue中。队列不受任何限制，可以存储任何数量的消息—本质上是一个无限制的缓存。很多producers可以通过同一个队列发送消息，相同的很多consumers可以从同一个队列上接收消息。<br>　　3. Consuming：消费者，consumer是基本属于等待接收消息的程序。<br>　　下面我们通过一张图看看java中使用rabbitmq的方式。<img src="/images/rabbitmq-flow.png" alt="rabbitmq-flow"></p>
<h2 id="u751F_u4EA7_u8005_u793A_u4F8B"><a href="#u751F_u4EA7_u8005_u793A_u4F8B" class="headerlink" title="生产者示例"></a>生产者示例</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Send</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 队列名称</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">"hello"</span>;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> java.io.IOException, TimeoutException </span>&#123;</span><br><span class="line">		<span class="comment">/**</span><br><span class="line">		 * 创建连接连接到MabbitMQ</span><br><span class="line">		 */</span></span><br><span class="line">		ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">		<span class="comment">// 设置MabbitMQ所在主机ip或者主机名</span></span><br><span class="line">		factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">		<span class="comment">// 创建一个连接</span></span><br><span class="line">		Connection connection = factory.newConnection();</span><br><span class="line">		<span class="comment">// 创建一个频道</span></span><br><span class="line">		Channel channel = connection.createChannel();</span><br><span class="line">		<span class="comment">// 指定一个队列</span></span><br><span class="line">		channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">		<span class="comment">// 发送的消息</span></span><br><span class="line">		String message = <span class="string">"hello world!"</span>;</span><br><span class="line">		<span class="comment">// 往队列中发出一条消息</span></span><br><span class="line">		channel.basicPublish(<span class="string">""</span>, QUEUE_NAME, <span class="keyword">null</span>, message.getBytes());</span><br><span class="line">		System.out.println(<span class="string">" [x] Sent '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">		<span class="comment">// 关闭频道和连接</span></span><br><span class="line">		channel.close();</span><br><span class="line">		connection.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>　　值得注意的是队列只会在它不存在的时候创建，多次声明并不会重复创建。信息的内容是字节数组，也就意味着你可以传递任何数据。</p>
<h2 id="u6D88_u8D39_u8005_u793A_u4F8B"><a href="#u6D88_u8D39_u8005_u793A_u4F8B" class="headerlink" title="消费者示例"></a>消费者示例</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Recv</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 队列名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">"hello"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> java.io.IOException, InterruptedException, TimeoutException </span>&#123;</span><br><span class="line">        <span class="comment">// 打开连接和创建频道，与发送端一样</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列，主要为了防止消息接收者先运行此程序，队列还不存在时创建队列。</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        System.out.println(<span class="string">" [*] Waiting for messages. To exit press CTRL+C"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建队列消费者</span></span><br><span class="line">        QueueingConsumer consumer = <span class="keyword">new</span> QueueingConsumer(channel);</span><br><span class="line">        <span class="comment">// 指定消费队列</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">true</span>, consumer);</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="comment">// nextDelivery是一个阻塞方法（内部实现其实是阻塞队列的take方法）</span></span><br><span class="line">            QueueingConsumer.Delivery delivery = consumer.nextDelivery();</span><br><span class="line">            String message = <span class="keyword">new</span> String(delivery.getBody());</span><br><span class="line">            System.out.println(<span class="string">" [x] Received '"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>　　开启RabbitMQ服务，分别运行Send.java和Recv.java，顺序无所谓。Recv启动后会阻塞，直到有新的消息进入，通过while循环重复获取。可以看到Recv打印消息： [x] Sent ‘hello world!’。示例代码：<a href="/code/rabbitmq-start.zip">rabbitmq-start.zip</a></p>
<h2 id="u53C2_u8003_u5730_u5740"><a href="#u53C2_u8003_u5730_u5740" class="headerlink" title="参考地址"></a>参考地址</h2><p><a href="http://blog.csdn.net/lmj623565791/article/details/37607165" target="_blank" rel="external">http://blog.csdn.net/lmj623565791/article/details/37607165</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/07/mq/1.RabbitMQ系列之入门/" data-id="cijzzpv9x008s1cfsryucpbd4" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mq/">mq</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/rabbitmq/">rabbitmq</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-nio/14.Grizzly" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2016/01/02/nio/14.Grizzly/" class="article-date">
  <time datetime="2016-01-02T06:00:00.000Z" itemprop="datePublished">2016-01-02</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/categories/nio/">nio</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2016/01/02/nio/14.Grizzly/">Grizzly概述</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="u7B80_u4ECB"><a href="#u7B80_u4ECB" class="headerlink" title="简介"></a>简介</h2><p>　　QuickServer是一个免费的开源Java库，用于快速创建健壮的多线程、多客户端TCP服务器应用程序。使用QuickServer，用户可以只集中处理应用程序的逻辑/协议，从而方便的建立功能强大的服务器应用。该程序由Akshathkumar Shetty设计和实现。</p>
<p>参考资料：<br><a href="http://m.blog.csdn.net/blog/huodianyan_11109/38019447#" target="_blank" rel="external">http://m.blog.csdn.net/blog/huodianyan_11109/38019447#</a><br><a href="http://blog.csdn.net/lizhi200404520/article/details/6701174" target="_blank" rel="external">http://blog.csdn.net/lizhi200404520/article/details/6701174</a><br><a href="http://adapterofcoms.iteye.com/blog/608114" target="_blank" rel="external">http://adapterofcoms.iteye.com/blog/608114</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2016/01/02/nio/14.Grizzly/" data-id="cijzzpv7o005y1cfsvk6bor54" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/xSocket/">xSocket</a></li></ul>

    </footer>
  </div>
  
</article>


  
  
    <nav id="page-nav">
      <a class="extend prev" rel="prev" href="/page/5/">&laquo; Prev</a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/4/">4</a><a class="page-number" href="/page/5/">5</a><span class="page-number current">6</span><a class="page-number" href="/page/7/">7</a><a class="page-number" href="/page/8/">8</a><span class="space">&hellip;</span><a class="page-number" href="/page/15/">15</a><a class="extend next" rel="next" href="/page/7/">Next &raquo;</a>
    </nav>
  
</section>
        
          <aside id="sidebar">
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/cache/">cache</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/database/">database</a><span class="category-list-count">13</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/docker/">docker</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/gis/">gis</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/git/">git</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/go/">go</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/gradle/">gradle</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/groovy/">groovy</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/hadoop/">hadoop</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/java/">java</a><span class="category-list-count">18</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/linux/">linux</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/log/">log</a><span class="category-list-count">11</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mongodb/">mongodb</a><span class="category-list-count">14</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mq/">mq</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/mybatis/">mybatis</a><span class="category-list-count">9</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/netty/">netty</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nginx/">nginx</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nio/">nio</a><span class="category-list-count">19</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/nodejs/">nodejs</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/redis/">redis</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/rpc/">rpc</a><span class="category-list-count">14</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/spring/">spring</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/tomcat/">tomcat</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/zookeeper/">zookeeper</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/杂项/">杂项</a><span class="category-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/aop/">aop</a><span class="tag-list-count">8</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/aspectj/">aspectj</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/cache/">cache</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/classloader/">classloader</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/common-loggings/">common-loggings</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/commonjs/">commonjs</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/database/">database</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/docker/">docker</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/dubbo/">dubbo</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/fastdfs/">fastdfs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gclib/">gclib</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/geohash/">geohash</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gis/">gis</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/git/">git</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/go/">go</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/gradle/">gradle</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/groovy/">groovy</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hadoop/">hadoop</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hessisan/">hessisan</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/">java</a><span class="tag-list-count">48</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/javassist/">javassist</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/kafka/">kafka</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/linux/">linux</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/log/">log</a><span class="tag-list-count">11</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/log4j/">log4j</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/logback/">logback</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/map/">map</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/memecached/">memecached</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mina/">mina</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mongodb/">mongodb</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mq/">mq</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mqtt/">mqtt</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mybatis/">mybatis</a><span class="tag-list-count">9</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/netty/">netty</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nginx/">nginx</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nio/">nio</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nodejs/">nodejs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/postgresql/">postgresql</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/protobuf/">protobuf</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/proxy/">proxy</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/push/">push</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/rabbitmq/">rabbitmq</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/redis/">redis</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/rpc/">rpc</a><span class="tag-list-count">14</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sitemesh/">sitemesh</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/sld/">sld</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/slf4j/">slf4j</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/socket/">socket</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spatialite-for-android/">spatialite for android</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spi/">spi</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/spring/">spring</a><span class="tag-list-count">13</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/tomcat/">tomcat</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/transaction/">transaction</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/web/">web</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/xSocket/">xSocket</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zbus/">zbus</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/zookeeper/">zookeeper</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/数据结构/">数据结构</a><span class="tag-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/aop/" style="font-size: 15.38px;">aop</a> <a href="/tags/aspectj/" style="font-size: 11.54px;">aspectj</a> <a href="/tags/cache/" style="font-size: 11.54px;">cache</a> <a href="/tags/classloader/" style="font-size: 10px;">classloader</a> <a href="/tags/common-loggings/" style="font-size: 10px;">common-loggings</a> <a href="/tags/commonjs/" style="font-size: 12.31px;">commonjs</a> <a href="/tags/database/" style="font-size: 16.92px;">database</a> <a href="/tags/docker/" style="font-size: 13.85px;">docker</a> <a href="/tags/dubbo/" style="font-size: 10px;">dubbo</a> <a href="/tags/fastdfs/" style="font-size: 10px;">fastdfs</a> <a href="/tags/gclib/" style="font-size: 10.77px;">gclib</a> <a href="/tags/geohash/" style="font-size: 10px;">geohash</a> <a href="/tags/gis/" style="font-size: 10px;">gis</a> <a href="/tags/git/" style="font-size: 10.77px;">git</a> <a href="/tags/go/" style="font-size: 10px;">go</a> <a href="/tags/gradle/" style="font-size: 10px;">gradle</a> <a href="/tags/groovy/" style="font-size: 10px;">groovy</a> <a href="/tags/hadoop/" style="font-size: 10px;">hadoop</a> <a href="/tags/hessisan/" style="font-size: 11.54px;">hessisan</a> <a href="/tags/java/" style="font-size: 20px;">java</a> <a href="/tags/javassist/" style="font-size: 10px;">javassist</a> <a href="/tags/kafka/" style="font-size: 11.54px;">kafka</a> <a href="/tags/linux/" style="font-size: 12.31px;">linux</a> <a href="/tags/log/" style="font-size: 17.69px;">log</a> <a href="/tags/log4j/" style="font-size: 12.31px;">log4j</a> <a href="/tags/logback/" style="font-size: 13.08px;">logback</a> <a href="/tags/map/" style="font-size: 10px;">map</a> <a href="/tags/memecached/" style="font-size: 10.77px;">memecached</a> <a href="/tags/mina/" style="font-size: 13.08px;">mina</a> <a href="/tags/mongodb/" style="font-size: 19.23px;">mongodb</a> <a href="/tags/mq/" style="font-size: 13.85px;">mq</a> <a href="/tags/mqtt/" style="font-size: 10.77px;">mqtt</a> <a href="/tags/mybatis/" style="font-size: 16.15px;">mybatis</a> <a href="/tags/netty/" style="font-size: 10px;">netty</a> <a href="/tags/nginx/" style="font-size: 11.54px;">nginx</a> <a href="/tags/nio/" style="font-size: 13.08px;">nio</a> <a href="/tags/nodejs/" style="font-size: 10px;">nodejs</a> <a href="/tags/postgresql/" style="font-size: 10.77px;">postgresql</a> <a href="/tags/protobuf/" style="font-size: 10px;">protobuf</a> <a href="/tags/proxy/" style="font-size: 10px;">proxy</a> <a href="/tags/push/" style="font-size: 10px;">push</a> <a href="/tags/rabbitmq/" style="font-size: 11.54px;">rabbitmq</a> <a href="/tags/redis/" style="font-size: 13.85px;">redis</a> <a href="/tags/rpc/" style="font-size: 19.23px;">rpc</a> <a href="/tags/sitemesh/" style="font-size: 10px;">sitemesh</a> <a href="/tags/sld/" style="font-size: 10px;">sld</a> <a href="/tags/slf4j/" style="font-size: 10px;">slf4j</a> <a href="/tags/socket/" style="font-size: 14.62px;">socket</a> <a href="/tags/spatialite-for-android/" style="font-size: 10px;">spatialite for android</a> <a href="/tags/spi/" style="font-size: 10px;">spi</a> <a href="/tags/spring/" style="font-size: 18.46px;">spring</a> <a href="/tags/tomcat/" style="font-size: 10.77px;">tomcat</a> <a href="/tags/transaction/" style="font-size: 10px;">transaction</a> <a href="/tags/web/" style="font-size: 10px;">web</a> <a href="/tags/xSocket/" style="font-size: 14.62px;">xSocket</a> <a href="/tags/zbus/" style="font-size: 10px;">zbus</a> <a href="/tags/zookeeper/" style="font-size: 10.77px;">zookeeper</a> <a href="/tags/数据结构/" style="font-size: 10.77px;">数据结构</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/01/">January 2016</a><span class="archive-list-count">67</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/12/">December 2015</a><span class="archive-list-count">81</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/11/">November 2015</a><span class="archive-list-count">2</span></li></ul>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recents</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2016/01/30/资料/">(no title)</a>
          </li>
        
          <li>
            <a href="/2016/01/30/java/13.Classloader系列一/">ClassLoader系列一</a>
          </li>
        
          <li>
            <a href="/2016/01/29/hadoop/1.hadoop系列之源码编译/">hadoop系列一之源码编译</a>
          </li>
        
          <li>
            <a href="/2016/01/29/go/1.GO系列之入门/">Go系列一之入门</a>
          </li>
        
          <li>
            <a href="/2016/01/28/tomcat/2.tomcat性能优化/">tomcat性能优化</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2016 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>